<template>
	<view class="container">
		<view class="swiper-box">
			<swiper :autoplay="false" :interval="3000" :duration="500" :current="swiperIndex" @change="swiperChange">
				<swiper-item v-if="goodsInfo && goodsInfo.videos">
					<view class="swiper-item videoBox">
						<video id="bannerId" :enable-progress-gesture="false" :controls="false"
							:show-center-play-btn="false" :src="$img_base_url(goodsInfo.videos)"></video>
						<!-- #ifdef MP-WEIXIN -->
						<view class="play_icon" @click.stop="playVideo" v-if="playIcon">
							<image :src="$img_path('/mall/3.png')" mode="widthFix"></image>
						</view>
						<!-- #endif -->
					</view>
				</swiper-item>
				<swiper-item v-for="(item, i) in goodsInfo.images" :key="i">
					<view class="swiper-item">
						<image :src="$img_base_url(item)" mode="aspectFill"></image>
					</view>
				</swiper-item>
			</swiper>
			<view class="dots" v-if="goodsInfo && goodsInfo.videos">
				<view class="video viewbox" :class="swiperIndex == 0 ? 'select' : ''" @click="checkSwiper(0)">
					视频
				</view>
				<view class="img viewbox" :class="swiperIndex > 0 ? 'select' : ''" @click="checkSwiper(1)">
					图集
				</view>
			</view>
			<view class="idx">
				<view class="i">
					{{ swiperIndex + 1 }}
				</view>
				<view class="all">
					{{
            goodsInfo && goodsInfo.images
              ? goodsInfo.videos
                ? Number(goodsInfo.images.length) + 1
                : goodsInfo.images.length
              : 0
          }}
				</view>
			</view>
		</view>

		<view class="content">
			<view class="box-1">
				<view class="price">
					<view class="left-num">
						<view class="p-1">
							￥
							<text>
								{{ minPrice ? minPrice[0] : "" }}
							</text>
							{{ minPrice ? minPrice[1] : "" }}
						</view>
						<text style="line-height: 66rpx; color: #e72a2a" v-if="maxPrice">-</text>
						<view class="p-1" v-if="maxPrice">
							￥
							<text>
								{{ maxPrice ? maxPrice[0] : "" }}
							</text>
							{{ maxPrice ? maxPrice[1] : "" }}
						</view>
						<view class="n-p"> ￥{{ market_price }} </view>
					</view>
					<view class="r-text"> 已拼{{ goodsInfo.sales || 0 }}件 </view>
				</view>
				<view class="name more-row" :style="{ '--row-num': 2 }">
					{{ goodsInfo.title || "" }}
				</view>
			</view>

			<view class="pt-list">
				<view class="title" @click="groupPopup">
					<text>{{ goodsInfo && goodsInfo.groups ? goodsInfo.groups.number : 0 }}人在拼，参与可立即拼成</text>
					<image :src="$img_path('/mall/4.png')" mode="widthFix"></image>
				</view>
				<view class="list" v-if="groupsInfo">
					<view class="item" v-for="(item, i) in groupsInfo.list" :key="item.id">
						<view class="left">
							<image :src="item.user && item.user.avatar ? $img_base_url(item.user.avatar) : ''"
								mode="aspectFill"></image>
							<text>{{ item.user ? item.user.nickname : "" }}</text>
						</view>
						<view class="right">
							<view class="time">
								<view class="num" v-if="item"> 还差{{ item.groups_num }}人拼成 </view>
								<wanl-timeout :endTime="item.validitytime" color="#333333" backgroundColor="#ffffff"
									borderColor="#ffffff" padding="0" margin="0" />
							</view>
							<button @click="addGroup(item, i)">参与拼单</button>
						</view>
					</view>
				</view>
			</view>

			<view class="model-box pj-box">
				<view class="title">
					<view class="l-text">
						商品评价<text>({{ statistics && statistics["total"] ? statistics["total"] : 0 }})</text>
					</view>
					<view class="r-i" @click="toEvaluate">
						<text>全部</text>
						<image :src="$img_path('/common/icon_r.png')" mode="widthFix"></image>
					</view>
				</view>
				<view class="pj-tag">
					<view class="t-item" :class="[commentTag == '' ? 'select' : '']" @click="pjTag('')">
						<text>全部</text>
					</view>
					<view class="t-item" :class="[commentTag == key ? 'select' : '']" v-for="(item, key) of c_tag"
						@click="pjTag(key)">
						<text>{{ item }}</text>
						<text>（{{ statistics && statistics[key] ? statistics[key] : 0 }}）</text>
					</view>
				</view>
				<view class="pj-list">
					<view class="item" v-for="(item, i) in comment_list" :key="item.id">
						<view class="user">
							<view class="left">
								<image :src="item.user && item.user.avatar ? $img_base_url(item.user.avatar) : ''"
									mode="aspectFill"></image>
								<view class="name-star">
									<text>{{ item.user.nickname }}</text>
									<view class="star">
										<uni-rate allow-half color="#DDDDDD" size="26" activeColor="#F2CB51"
											:value="item.score" />
										<!-- <image v-for="(item,i) in 5" :key="i" :src="i<4 ? $img_path('/common/star_1.png') : $img_path('/common/star_2.png')" mode="widthFix"></image> -->
									</view>
								</view>
							</view>
							<view class="time">
								{{ $dayjs.unix(item.createtime).format("YYYY-MM-DD") }}
							</view>
						</view>
						<view class="con">
							<view class="text">
								{{ item.content }}
							</view>
							<view class="img">
								<view class="i-box" @click="preview(item.images)">
									<image :src="$img_base_url(item.images[0])" mode="widthFix"></image>
									<text>{{ item.images.length }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="model-box info-box" style="padding:20rpx 0">
				<view class="title">
					<view class="l-text" style="padding-left: 20rpx"> 商品详情 </view>
				</view>
				<view class="con">
					<rich-text :nodes="goodsInfo.content || ''"></rich-text>
				</view>
			</view>

			<view class="other-goods">
				<view class="title"> 您可能还会喜欢 </view>
				<view class="g-list">
					<view class="item" v-for="(item, i) in like_list" :key="item.id">
						<MallItemBox :styleType="1" :title_row="1" :goodsDetail="item"
							:imageStyle="{ width: '344rpx', height: '344rpx' }">
							<!-- <text slot="center" style="margin-top: 16rpx;display: block;">销量：1000</text>
							<view slot="tagList" class="tagList">
								<view class="tag-item">
									标签标签
								</view>
								<view class="tag-item">
									标签
								</view>
								<view class="tag-item">
									标签标签
								</view>
							</view> -->
						</MallItemBox>
					</view>
				</view>
			</view>
		</view>

		<view class="bottom-btn pb-con">
			<view class="b-box pb-con">
				<view class="con-box">
					<view class="left">
						<view class="i-box">
							<image :src="$img_path('/mall/7.png')" mode="widthFix"></image>
							<text>客服</text>
						</view>
						<view class="i-box" @click="shareShow">
							<image :src="$img_path('/mall/8.png')" mode="widthFix"></image>
							<text>分享</text>
						</view>
						<view class="i-box" @click="followClick">
							<image v-if="goodsInfo.follow" :src="$img_path('/mall/6.png')" mode="widthFix"></image>
							<image v-else :src="$img_path('/common/star_2.png')" mode="widthFix"></image>
							<!-- <text>100</text> -->
							<text>{{ goodsInfo.follow ? "取消" : "收藏" }}</text>
						</view>
					</view>

					<view class="right">
						<view class="a-box">
							<view class="l-b" v-if="goodsInfo.is_alone === 1" @click="selectSpec(3)">
								<text>直接购买</text>
							</view>
							<view class="r-b" :style="{ width: goodsInfo.is_alone === 1 ? '' : '100%' }"
								@click="selectSpec(2)">
								<text>拼团购买</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<popupBox ref="groupBuy" type="center" :isSlot="true">
			<view class="buy-box">
				<view class="title">
					<text>可参与的拼单</text>
					<image :src="$img_path('/mall/10.png')" @click="$refs.groupBuy.close()" mode="widthFix"></image>
				</view>
				<view class="list">
					<scroll-view class="list-scroll" scroll-y="true" v-if="goodsInfo.groups">
						<view class="item" v-for="(item, i) in goodsInfo.groups ? goodsInfo.groups.list : []"
							:key="item.id">
							<view class="left">
								<image :src="item.user && item.user.avatar ? $img_base_url(item.user.avatar) : ''"
									mode="widthFix"></image>
								<view class="t-con">
									<view class="name" v-if="item">
										<text>{{ item.user ? item.user.nickname : "" }}</text>
										<text>还差{{ item.groups_num }}人拼成</text>
									</view>
									<view class="time">
										<wanl-timeout :endTime="item.validitytime" color="#333333"
											backgroundColor="#ffffff" tipsContent="剩余" companyColor="#333333"
											borderColor="#ffffff" padding="0" margin="0" />
									</view>
								</view>
							</view>
							<view class="r-btn">
								<button @click="addGroup(item, i)">参与拼团</button>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</popupBox>

		<popupBox ref="SubmitBuy" type="center" :isSlot="true">
			<view class="buy-box submit-buy">
				<view class="title">
					<text>参与昵称昵称的拼单</text>
					<image :src="$img_path('/mall/10.png')" @click="closeBuy" mode="widthFix"></image>
				</view>
				<view class="con">
					<view class="end-text display-flex alig center" v-if="n_group_info"> 仅剩{{ n_group_info.groups_num }}个名额，<wanl-timeout :endTime="n_group_info.validitytime" color="#333333" backgroundColor="#ffffff"
									borderColor="#ffffff" padding="0" margin="0" />后结束 </view>

					<view class="user-box" v-if="n_group_info">
						<view class="u-item">
							<image
								:src="n_group_info && n_group_info.user ? $img_base_url(n_group_info.user.avatar) : ''"
								mode="widthFix"></image>
							<text>拼主</text>
						</view>
						<view class="u-item" v-for="(item, i) in n_group_info.join_num - n_group_info.groups_num"
							:key="i">
							<image :src="$img_path('/mall/avatar.png')" mode="widthFix"></image>
						</view>
						<view class="u-item" v-for="(item, i) in n_group_info.groups_num" :key="i">
							<image :src="$img_path('/mall/11.png')" mode="widthFix"></image>
						</view>
					</view>
					<view class="btn">
						<button @click="submitGroup">参与拼单</button>
					</view>
				</view>
			</view>
		</popupBox>
		<!-- 分享 -->
		<popupBox ref="share" type="bottom" :isSlot="true">
			<view class="shareBox">
				<view class="title">
					<text>分享到</text>
					<!-- <image src="@/static/image/login_1.png" @click="$refs.share.close()" mode="widthFix"></image> -->
				</view>
				<view class="box">
					<view class="item" @click="shareClick('WXSceneSession')">
						<image :src="$img_path('/course/classify/1.png')" mode="widthFix"></image>
						<text>微信好友</text>
						<!-- #ifdef MP-WEIXIN -->
						<button open-type="share"></button>
						<!-- #endif -->
					</view>
					<view class="item" @click="shareClick('WXSceneTimeline')">
						<image :src="$img_path('/course/classify/2.png')" mode="widthFix"></image>
						<text>朋友圈</text>
					</view>
					<view class="item" @click="createdImg()">
						<image :src="$img_path('course/classify/3.png')" mode="widthFix"></image>
						<text>生成海报</text>
					</view>
				</view>
				<view class="btn">
					<button @click="$refs.share.close()">取消</button>
				</view>
			</view>
		</popupBox>

		<!-- 海报弹窗 -->
		<popupBox ref="haibao" type="bottom" backgroundColor="#FFFFFF00" customClass="hbpopup" :isSlot="true">
			<view class="haibao">
				<view class="canvas_content">
					<image :src="canvas_img_url" mode="widthFix"></image>
				</view>

				<view class="shareBox hb_b">
					<view class="title">
						<text>分享当前图片到</text>
						<!-- <image src="@/static/image/login_1.png" @click="$refs.haibao.close()" mode="widthFix"></image> -->
					</view>
					<view class="box">
						<view class="item" @click="saveCanvasImg()">
							<image :src="$img_path('course/classify/4.png')" mode="widthFix"></image>
							<text>保存图片</text>
						</view>
						<view class="item" @click="shareClick('WXSceneSession')">
							<image :src="$img_path('/course/classify/1.png')" mode="widthFix"></image>
							<text>微信好友</text>
							<!-- #ifdef MP-WEIXIN -->
							<button open-type="share"></button>
							<!-- #endif -->
						</view>
						<view class="item" @click="shareClick('WXSceneTimeline')">
							<image :src="$img_path('/course/classify/2.png')" mode="widthFix"></image>
							<text>朋友圈</text>
						</view>
					</view>
					<view class="btn">
						<button @click="$refs.haibao.close()">取消</button>
					</view>
				</view>
			</view>
		</popupBox>

		<view class="jiantou" v-if="pengyouquan" @click="pengyouquan = false">
			<image :style="{ top: 5 + 'px', right: jWidth + 'px' }" :src="$img_path('/course/jian.png')"
				mode="widthFix"></image>
			<view class="text"> 请点击这里 </view>
		</view>

		<!-- 规格选择 -->
		<goodsSelect ref="selectGoods" :selectGood="selectGood" :goodsInfo="goodsInfo" @submitOrder="submitOrder">
		</goodsSelect>

		<canvas canvas-id="offlineCanvas"
			style="width: 634px; height: 968px; position: fixed; z-index: -1; opacity: 0; background-color: #ffffff"></canvas>
	</view>
</template>

<script>
	const FormData = require("@/utils/formdata/index.js");
	import {
		productGoodsDetail,
		getLikes,
		groupsOrderGoodsList,
		groupFollowApi
	} from "@/utils/api/mallApi.js";
	import canvas_img from "@/utils/canvas_img";
	import goodsSelect from "@/components/popup/goods-select.vue";
	import MallItemBox from "@/components/service-box/mall-item-box.vue";
	import popupBox from "../../components/popup/popup.vue";
	import wanlTimeout from "@/components/wanl-timeout/wanl-timeout.vue";
	import {
		IMG_BASE_URL,
		BASE_URL
	} from "@/utils/env.js";
	export default {
		components: {
			MallItemBox,
			popupBox,
			goodsSelect,
			wanlTimeout,
		},
		data() {
			return {
				jWidth: this.jWidth - 30,
				videoDom: null,
				playIcon: true,
				swiperIndex: 0,

				canvas_img_url: "", //海报本地url
				pengyouquan: false, //朋友圈分享指引

				goods_id: null,
				minPrice: "",
				maxPrice: "",
				market_price: "",
				goodsInfo: {},
				groupsInfo: null,
				selectGood: [],
				c_tag: {
					good: "好评",
					pertinent: "中评",
					poor: "差评",
					figure: "有图",
				},
				commentTag: "", //good=好评,pertinent=中评,poor=差评,figure=有图
				statistics: {},
				comment_list: [],

				like_list: [],
				page: 1,
				last_page: 0,
				total: 0,
				contentText: {
					contentdown: "上滑加载更多",
					contentrefresh: "加载中",
					contentnomore: "没有更多了",
				},
				like_status: "",

				n_group_info: null, //拼团信息
				order_status: null, //1参与拼团，2单独拼团，3直接购买
			};
		},
		computed: {
			getSelectGoods() {
				if (this.goodsInfo && this.goodsInfo.sku) {
					return this.goodsInfo.sku.filter((e) => {
						return this.compareArrays(e.difference, this.selectGood);
					})[0];
				}
			},
		},
		onLoad(data) {
			this.goods_id = data.id;
		},
		onShow() {
			this.videoDom = uni.createVideoContext("bannerId");
			this.getDetail();
			this.getLikes();
		},
		//分享朋友圈
		onShareTimeline(res) {
			return {
				title: this.goodsInfo.name, //分享的标题
				imageUrl: this.$img_base_url(this.goodsInfo.image), //展示的图片，这里是本地路径的写法，也可以写http或https开头的图片路径
				query: `pagesMall/group_buying/detail?id=${this.goods_id}`, //页面打开的传参
			};
		},
		// 分享到好友
		onShareAppMessage(res) {
			return {
				title: this.goodsInfo.name, //分享的标题
				imageUrl: this.$img_base_url(this.goodsInfo.image), //展示的图片，这里是本地路径的写法，也可以写http或https开头的图片路径
				path: `pagesMall/group_buying/detail?id=${this.goods_id}`, //点击链接后跳转的页面，可以带参数
			};
		},
		// 滚动到底部
		onReachBottom(e) {
			if (this.page < this.last_page) {
				this.page++;
				this.getLikes();
			}
		},
		methods: {
			playVideo() {
				this.videoDom.play();
				this.playIcon = false;
			},

			// 猜你喜欢
			getLikes() {
				this.like_status = "contentrefresh";
				getLikes({
					pages: "cart",
					page: this.page,
				}).then((res) => {
					this.last_page = res.data.last_page;
					this.total = res.data.total;
					if (this.page == 1) {
						this.like_list = res.data.data;
					} else {
						this.like_list = [...res.data.data, ...this.like_list];
					}
					if (this.page < res.data.last_page) {
						this.like_status = "contentdown";
					} else {
						this.like_status = "contentnomore";
					}
				});
			},
			// 商品详情
			getDetail() {
				let formData = new FormData();
				formData.append("id", this.goods_id);
				uni.showLoading();
				// productGoodsDetail(formData.getData()).then(res=>{
				productGoodsDetail({
					id: this.goods_id
				}).then((res) => {
					// console.log(res,'--')
					uni.hideLoading();
					this.goodsInfo = res.data;
					this.groupsInfo = res.data.groups;
					// 价格区间
					if (res.data.sku.length == 0) {
						this.minPrice = res.data.price;
						this.market_price = res.data.price;
					} else {
						let price = [],
							market_price = [];
						for (let value of res.data.sku) {
							price.push(value.price);
							market_price.push(value.market_price);
						}
						let minPrice = Math.min.apply(null, price),
							maxPrice = Math.max.apply(null, price),
							maxMarketPrice = Math.max.apply(null, market_price);

						this.minPrice = this.gPrice(Number(minPrice).toFixed(2));
						this.maxPrice = minPrice == maxPrice ? "" : this.gPrice(Number(maxPrice).toFixed(2));
						this.market_price = Number(maxMarketPrice).toFixed(2); //最大市场价
						// res.data.interval_price = minPrice == maxPrice ? Number(minPrice).toFixed(2) : ( minPrice + '-' + Number(maxPrice).toFixed(2) ); //区间价格
						// res.data.market_price = Number(maxMarketPrice).toFixed(2); //最大市场价
					}
					this.selectGood = res.data.sku[0].difference;
				});
			},

			// 商品收藏/取消收藏
			followClick() {
				uni.showLoading();
				groupFollowApi({
					id: this.goods_id
				}).then((res) => {
					uni.showToast({
						title: res.data ? "收藏成功" : "取消收藏成功",
						icon: "none",
					});
					this.goodsInfo.follow = res.data;
					// uni.hideLoading();
					// this.getDetail();
				});
			},
			// 参与拼团
			addGroup(data, i) {
				this.$refs.SubmitBuy.open();
				this.n_group_info = data;
				console.log(data,'参与拼团参与拼团参与拼团')
			},
			closeBuy() {
				this.$refs.SubmitBuy.close();
			},

			// 提交拼团
			submitGroup() {
				this.order_status = 1;
				this.$refs.selectGoods.open();
			},
			submitOrder(data) {
				console.log(data, "---", this.n_group_info);
				// return
				let arr = [{
					...data,
					goods_id: this.goods_id,
					type: this.order_status == 3 ? "alone" : "group",
					groups_id: this.n_group_info ? this.n_group_info.id : "",
				}, ];
				uni.navigateTo({
					url: `/pagesMall/order/confirm_group_order?id=${this.goods_id}&data=${JSON.stringify(arr)}&type=${
          this.order_status == 3 ? "alone" : "group"
        }`,
				});
			},

			checkSwiper(i) {
				this.swiperIndex = i;
				this.videoDom.pause();
				this.playIcon = true;
			},
			swiperChange(val) {
				let {
					current
				} = val.detail;
				this.swiperIndex = current;
				this.videoDom.pause();
				this.playIcon = true;
			},

			groupPopup() {
				this.$refs.groupBuy.open();
			},

			selectSpec(status) {
				this.n_group_info = null;
				this.order_status = status;
				console.log(status, "-----");
				this.$refs.selectGoods.open("group", 0, status == 3 ? "alone" : "");
			},

			toEvaluate() {
				uni.navigateTo({
					url: "/pagesMall/evaluate/evaluate",
				});
			},

			shareShow() {
				this.$refs.share.open();
			},

			shareClick(text) {
				if (text == "WXSceneTimeline") {
					console.log("-------");
					this.pengyouquan = true;
				}
			},

			// 生成海报
			async createdImg() {
				uni.showLoading({
					title: "生成中...",
				});
				this.getQrcodeImg().then((qrcode) => {
					let data = {
						url: this.$img_base_url(this.goodsInfo.image),
						salePrice: this.getSelectGoods.price,
						market_price: this.getSelectGoods.market_price,
						name: this.goodsInfo.title,
						sales: this.goodsInfo.sales,
						qrcode: qrcode,
					};
					canvas_img.initCanvas("offlineCanvas", this, data).then((res) => {
						uni.canvasToTempFilePath({
							canvasId: "offlineCanvas",
							// x: 0,
							// y: 0,
							// width: 634,
							// height: 963,
							success: (res) => {
								console.log(res);
								this.canvas_img_url = res.tempFilePath;
								uni.hideLoading();
								this.$refs.haibao.open();
							},
						});
					});
				});
			},

			getQrcodeImg() {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: BASE_URL +
							`/api/wanlshop/common/qrcode?width=80&page=pagesMall/group_buying/detail?id=${this.goods_id}&qr=g`,
						success: (data) => {
							resolve(data.path);
						},
						fail: (err) => {
							reject(err);
							uni.showToast({
								title: "海报生成失败",
								mask: false,
								duration: 2000,
								icon: "none",
							});
							uni.hideLoading();
						},
					});
				});
			},

			saveCanvasImg() {
				uni.saveImageToPhotosAlbum({
					filePath: this.canvas_img_url,
					success: function(res) {
						var savedFilePath = res.savedFilePath;
					},
				});
			},
		},
	};
</script>
<style lang="scss">
	@import "detail.scss";

	.swiper-box {
		height: 700rpx !important;
	}

	.swiper-item {
		height: 100%;

		image {
			height: 100% !important;
		}
	}
</style>